import feedparser 
import time
from thesocialstockmarket.users.models import *
from thesocialstockmarket.recommendation.models import *
from thesocialstockmarket.recommendation.ystockquote import get_all

STOCKS = (('GOOG', 'Google'),
        ('YAHO', 'Yahoo'),
        )

def create_stock_if_dont_exists(name, company):
    try:
        stock = Stock.objects.get(stock_name = name)
    except Stock.DoesNotExist:
        stock = Stock(stock_name = name, stock_companyname = company)
        stock.save()
    return stock
    
        
def importStock(stock):
    dict = get_all(stock.stock_name)
    flu = Fluct(
            stock =  stock,
            price = dict['price'] if dict['price'] != 'N/A' else None,
            change = dict['change'] if dict['change'] != 'N/A' else None,
            volume = dict['volume'] if dict['volume'] != 'N/A' else None,
            avg_daily_volume = dict['avg_daily_volume'] if dict['avg_daily_volume'] != 'N/A' else None,
            stock_exchange = dict['stock_exchange'] if dict['stock_exchange'] != 'N/A' else None,
            market_cap = dict['market_cap'] if dict['market_cap'] != 'N/A' else None,
            book_value = dict['book_value'] if dict['book_value'] != 'N/A' else None,
            ebitda = dict['ebitda'] if dict['ebitda'] != 'N/A' else None,
            dividend_per_share = dict['dividend_per_share'] if dict['dividend_per_share'] != 'N/A' else None,
            dividend_yield = dict['dividend_yield'] if dict['dividend_yield'] != 'N/A' else None,
            earnings_per_share = dict['earnings_per_share'] if dict['earnings_per_share'] != 'N/A' else None,
            week52_high = dict['52_week_high'] if dict['52_week_high'] != 'N/A' else None,
            week52_low = dict['52_week_low'] if dict['52_week_low'] != 'N/A' else None,
            day50_moving_avg = dict['50day_moving_avg'] if dict['50day_moving_avg'] != 'N/A' else None,
            day200_moving_avg = dict['200day_moving_avg'] if dict['200day_moving_avg'] != 'N/A' else None,
            price_earnings_ratio = dict['price_earnings_ratio'] if dict['price_earnings_ratio'] != 'N/A' else None,
            price_earnings_growth_ratio = dict['price_earnings_growth_ratio'] if dict['price_earnings_growth_ratio'] != 'N/A' else None,
            price_sales_ratio = dict['price_sales_ratio'] if dict['price_sales_ratio'] != 'N/A' else None,
            price_book_ratio = dict['price_book_ratio'] if dict['price_book_ratio'] != 'N/A' else None,
            short_ratio = dict['short_ratio'] if dict['short_ratio'] != 'N/A' else None,
            )
    flu.save()
    print stock.stock_name + ": " + flu.price
    
    
     
def save_once():
    for entry in STOCKS:
        stock = create_stock_if_dont_exists(entry[0], entry[1])
        importStock(stock)

def save_continuously():
    while True:
        save_once()
	time.sleep(60000)
